<template>
	<div class="main">
		<div class="login-wrapper">
			<Form class="layui-form">
				<h2>用户登录</h2>
				<div style="margin-bottom:20px;">
					<TextBox
						v-model="username"
						placeholder="用户名"
						iconCls="icon-man"
						style="width: 100%;"
					></TextBox>
				</div>
				<div style="margin-bottom:20px">
					<PasswordBox
						v-model="password"
						placeholder="密码"
						style="width: 100%;"
					></PasswordBox>
				</div>

				<div style="margin-bottom:20px">
					<TextBox v-model="code" placeholder="验证码" style="width: 160px;"></TextBox>
					<img
						:src="base64"
						@click="refreshKaptcha()"
						style="width: 160px;height: 30px;"
						class="f-field textbox f-inline-row"
					/>
				</div>

				<div style="margin-bottom:20px">
					<LinkButton @click="submitForm()" class="e-l-btn">登录</LinkButton>
				</div>
			</Form>
		</div>
	</div>
</template>

<script>
export default {
	created() {
		this.$e.jumpway.toCondition("home", null, !this.$user.isGuest());
		this.refreshKaptcha();
	},
	data() {
		return {
			username: '',
			password: '',
			base64: '',
			token: '',
			code: ''
		};
	},
	methods: {
		refreshKaptcha: function() {
			this.$e.api.loginCaptcha().then(res => {
				var [data] = res;
				this.base64 = 'data:image/png;base64,' + data.base64;
				this.token = data.token;
				this.code = '';
			});
		},
		submitForm: function() {
			this.$e.api
				.login({
					username: this.username,
					password: this.password,
					token: this.token,
					code: this.code
				})
				.then(res => {
					var [data, code, message] = res;
					if (code !== 200) {
						this.refreshKaptcha()
						this.$toast.center(message);
					}

					if (code === 200) {
						this.$store.dispatch('save', { name: 'vuex_token', value: data.token });
						this.$user.login(data.user, data.token);
						this.$e.jumpway.to("home");
					}
				});
		}
	}
};
</script>

<style scoped="scoped">
@import url('../assets/login.css');
.main {
	background-image: url(../assets/bg.jpg);
	background-repeat: no-repeat;
	background-size: cover;
	min-height: 100vh;
}
</style>
